package com.yoosora.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D.Double;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

public class ImageUtils {
	private BufferedImage bi = null;
	/**
	 *抗锯齿
	 */
	private RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	
	private String satori = "images/satori.png";
	
	public static ImageUtils builder(){
		return new ImageUtils();
	}
	
	public ImageUtils satoriThrow(String avatarString) throws IOException {
		BufferedImage avatar = ImageIO.read(new URL(avatarString));
		BufferedImage avaImg = new BufferedImage(avatar.getWidth(), avatar.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
		BufferedImage satoriImg = ImageIO.read(Objects.requireNonNull(this.getClass().getClassLoader().getResource(satori)));
		//头像画圆
		Double aDouble = new Double(0.0, 0.0, avaImg.getWidth(), avaImg.getHeight());
		//获取绘制器
		Graphics2D graphics = avaImg.createGraphics();
		//设置抗锯齿
		graphics.setRenderingHints(renderingHints);
		//剪切图片
		graphics.clip(aDouble);
		graphics.drawImage(avatar, 0, 0, null);
		graphics.dispose();
		//绘制结束
		BufferedImage proceedAva = Thumbnails.of(avaImg)
				//设置大小
				.size(138, 138)
				//随机旋转
				.rotate(Math.random() * 360.00)
				.asBufferedImage();
		proceedAva = Thumbnails.of(proceedAva)
				.sourceRegion(Positions.CENTER, 138, 138)
				.size(138, 138)
				.keepAspectRatio(false)
				.asBufferedImage();
		Graphics2D bgImgGraphics = satoriImg.createGraphics();
		bgImgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
		bgImgGraphics.drawImage(proceedAva, 18, 180, 138, 138, null);
		// 结束绘制图片
		bgImgGraphics.dispose();
		// 将内存中图片写入data中
		bi =  Thumbnails.of(satoriImg)
				.size(512, 512)
				.asBufferedImage();
		return this;
	}
	
	public BufferedImage build(){
			return bi;	
	}
}
